package com.mtbu.comm;

import java.util.HashMap;


import my.myorm.tool.jdbc.DefaultBean;
import my.myorm.tool.jdbc.SQLExecutor;
import my.myorm.tool.jdbc.SQLManager;

import com.mtbu.bean.PageCacheBean;
import com.util.MD5Util;
import com.util.SuperString;

public class PageCache {	
	private static HashMap<String, PageCacheBean> cache = new HashMap<String, PageCacheBean>();
	
	public static int getPageCountBySql(String sql,String countfield,String dsname){
		int count = 0;
		try{
			String key = MD5Util.encode(sql.getBytes("utf-8"));
			if(cache.containsKey(key)){
				PageCacheBean pcb = cache.get(key);
				count = pcb.getCount();
				if(pcb.getTimestamp()<System.currentTimeMillis()){
					new RefreshCacheThread(sql,key,countfield,dsname).start();
				}
			}else{
				count = getCountFromDB(sql,countfield,dsname);
				refreshCache(key,count);
			}
		}catch (Exception e) {
			e.printStackTrace();
			return count;
		}
		return count;
	}
	
	private static int getCountFromDB(String sql,String countfield,String dsname){
		int allCount = 0;
		try{
			SQLExecutor dbconn = null;
			if(dsname!=null && !dsname.equals("")) dbconn = SQLManager.getSQLExecutor(dsname);
			else dbconn = SQLManager.getSQLExecutor();
			String countsql="select count(" + countfield + ") as totalcount "+getSuffixSqlForTotal(sql);
	        allCount = dbconn.queryForBean(countsql, DefaultBean.class).getInt("totalcount");
		}catch (Exception e) {
			e.printStackTrace();
			return allCount;
		}
        return allCount;
	}
	private static class RefreshCacheThread extends Thread{
        private String sql = null;
        private String countfield=null;
        private String dsname=null;
        private String key=null;
        public RefreshCacheThread(String sql,String key,String countfield,String dsname){
            this.sql=sql;
            this.key=key;
            this.countfield=countfield;
            this.dsname=dsname;
        }
        public void run(){
        	int allcount = getCountFromDB(sql, countfield,dsname);
        	refreshCache(key,allcount);
        }
    }
	private static void refreshCache(String key,int allcount){
		PageCacheBean pcb = new PageCacheBean();
    	pcb.setCount(allcount);
    	pcb.setTimestamp(System.currentTimeMillis()+SuperString.getInt(Util.getProperties("PAGE_CACHE_TIMESTAMP")));
    	cache.put(key, pcb);
	}
	
	private static String getSuffixSqlForTotal(String sql){
        String lowercaseSql=sql.toLowerCase();
        int formIndex=lowercaseSql.indexOf(" from ");
        int orderbyIndex=lowercaseSql.indexOf(" order by ");
        int groupbyIndex=lowercaseSql.indexOf(" group by ");
        String suffixsql="";
        if(orderbyIndex>0){
             suffixsql=sql.substring(formIndex,orderbyIndex);
        }else{
             suffixsql=sql.substring(formIndex);
        }
        if(groupbyIndex>0){
             suffixsql="from (" +(orderbyIndex> 0?sql.substring(0,orderbyIndex) :sql) + ") as a";
        }
        return suffixsql;
    }
}
